package com.aikon.wht.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by haitao.wang on 2016/12/15.
 */
@Component
@RequestMapping("/error")
public class MyErrorController implements ErrorController {

    private static Logger logger = LoggerFactory.getLogger(MyErrorController.class);

    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return "myError";
    }

    @RequestMapping(produces = "test/html", value = "/404")
    public String myError404(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        response.setStatus(getStatus(request).value());
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        modelMap.addAttribute("msg", errorAttributes.getErrorAttributes((WebRequest) requestAttributes, true).toString());
        return "myError404";
    }

    @RequestMapping(produces = "test/html", value = "/myError")
    public String myError() {
        return "myError";
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
